/*
** exec_com.c for minishell2 in /home/lingla_j/work/tutorat/env
** 
** Made by julien linglain
** Login   <lingla_j@epitech.net>
** 
** Started on  Tue Feb 28 18:12:48 2012 julien linglain
** Last update Fri Apr  6 12:17:11 2012 julien linglain
*/

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <dirent.h>
#include "mysh.h"

int		count_path(char *path, char sep)
{
  int		i;
  int		nb_path;

  i = 0;
  nb_path = 1;
  while (path[i] != '\0')
    {
      if (path[i] == sep)
        nb_path++;
      i++;
    }
  return (nb_path);
}

char		**cut_path(char *path, char sep)
{
  int		i;
  int		j;
  int		k;
  char		**bin_path;

  i = 0;
  j = 0;
  k = 0;
  bin_path = xmalloc(sizeof(char*) * count_path(path, sep) + 1);
  while (path[i] != '\0')
    {
      while (path[i] != '\0' && path[i] == sep)
	i++;
      j = i;
      while (path[i] != '\0' && path[i] != sep)
	i++;
      if ((i - j) != 0)
	{
	  bin_path[k] = xmalloc(sizeof(char) * (i - j + 1));
	  strncpy(bin_path[k], &path[j], i - j);
	  k++;
	}
    }
  bin_path[k] = NULL;
  return (bin_path);
}

char		*search_bin_path(char **tab, char *bin)
{
  char		*path;
  struct dirent	*rd;
  DIR		*dir;
  int		i;

  i = 0;
  while (tab[i] != NULL)
    {
      dir = opendir(tab[i]);
      if (dir == NULL)
        {
          my_puterror("Error on opening directory : ");
          my_puterror(tab[i]);
	  my_puterror("\n");
          return (NULL);
        }
      while ((rd = readdir(dir)))
	{
	  if (my_strcmp(rd->d_name, bin) == 0)
	    return (tab[i]);
	}
      closedir(dir);
      i++;
    }
  return (NULL);
}

int		my_exec(char *bin_path, char **av)
{
  pid_t		pid;
  int		status;
  pid_t		w;
  extern char	**environ;

  if ((pid = !fork()))
    {
      if (execve(bin_path, av, environ) == -1)
	my_puterror("Command not found.\n");
      exit(0);
    }
  else
    {
      w = waitpid(pid, &status, WUNTRACED | WCONTINUED);
      if (w == -1)
	{
	  my_puterror("Error on Waitpid.\n");
	  exit(EXIT_FAILURE);
	}
      if (WEXITSTATUS(status) == 2)
	return (EXIT_FAILURE);
    }
  return (EXIT_SUCCESS);
}

int		exec_com(int ac, char **av, char *s, t_list *env)
{
  char		*path;
  char		**tab_bin_path;
  char		*bin_path;

  path = getvalue(env, "PATH");
  if (path == NULL && !check_if_path(av[0]))
    my_path_var_empty();
  else if (check_if_path(av[0]))
    my_exec_with_path(av);
  else
    {
      tab_bin_path = cut_path(path, ':');
      bin_path = search_bin_path(tab_bin_path, av[0]);
      if (bin_path != NULL)
	{
	  bin_path = my_strcat(bin_path, "/");
	  bin_path = my_strcat(bin_path, av[0]);
	  my_exec(bin_path, av);
	}
      else
	my_puterror("Command not found.\n");
    }
  return (EXIT_SUCCESS);
}
